import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/common/Home.vue'),
    meta: {
      title: '首页',
      requiresAuth: true // 需要登录
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/common/Login.vue'),
    meta: {
      title: '登录',
      requiresAuth: false // 不需要登录
    }
  },
  {
    path: '/form',
    name: 'Form',
    component: () => import('@/views/form/BasicForm.vue'),
    meta: {
      title: '信息填写',
      requiresAuth: false, // 不需要登录 - 公开页面
      isPublic: true
    }
  },
  {
    path: '/success',
    name: 'Success',
    component: () => import('@/views/common/Success.vue'),
    meta: {
      title: '提交成功',
      requiresAuth: false // 不需要登录
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/common/NotFound.vue'),
    meta: {
      title: '页面不存在',
      requiresAuth: false
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior() {
    return { top: 0 }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  if (to.meta?.title) {
    document.title = `${to.meta.title} - 微信服务号`
  }
  
  // 动态导入 auth store 避免循环依赖
  const { useAuthStore } = await import('@/store/auth')
  const authStore = useAuthStore()
  
  // 公开页面白名单 - 这些页面不需要登录
  const publicRoutes = ['/login', '/form', '/success', '/404']
  
  // 检查是否为公开页面
  if (publicRoutes.includes(to.path) || to.meta?.isPublic || to.meta?.requiresAuth === false) {
    next()
    return
  }
  
  // 检查登录状态
  if (!authStore.checkAuth()) {
    // 未登录，跳转到登录页，并保存目标路由
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return
  }
  
  // 已登录，正常访问
  next()
})

export default router